package com.example.demo.demos.web.controller;

import com.example.demo.demos.web.po.Invoice;
import com.example.demo.demos.web.util.PdfGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;

@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @Autowired
    private SpringTemplateEngine templateEngine;

    @PostMapping("/generate")
    public ResponseEntity<String> generatePdf(@RequestBody Invoice invoice) {
        try {
            Context context = new Context();
            context.setVariable("invoice", invoice);
            String html = templateEngine.process("invoice", context);
            System.out.println(html);

            String outputPath = System.getProperty("user.dir") + File.separator + "PDF"+ File.separator + "invoice.pdf";
            PdfGenerator.generatePdf(html, outputPath);

            return ResponseEntity.ok("PDF 生成成功，路径：" + outputPath);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("生成失败: " + e.getMessage());
        }
    }
}
